﻿ //===============================BitFlipNoiseAlgorithm.cs==============================\\
//===Michiel van der Winden======\\

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace Team2_Vision
{
    class BitFlipNoise : VisionAlgorithm
    {
        public BitFlipNoise(String name) : base(name) { }
        public override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage, int intensity)
        {
            int sizeMap = ((sourceImage.Width * sourceImage.Height) / 500);
            Random random = new Random();
            Bitmap returnImage = new Bitmap(sourceImage);
            for (int i = 0; i < (sizeMap * intensity); i++)
            {
                int x = random.Next(0, sourceImage.Width);
                int y = random.Next(0, sourceImage.Height);
                Color oldColor = sourceImage.GetPixel(x, y);
                byte rValue = oldColor.R;
                byte gValue = oldColor.G;
                byte bValue = oldColor.B;
                byte[] color = colorNoiseChange(rValue, gValue, bValue);
                int redValue = (int)(color[0]);
                int greenValue = (int)(color[1]);
                int blueValue = (int)(color[2]);
                Color newColor = new Color();
                newColor = Color.FromArgb(redValue, greenValue, blueValue);
                returnImage.SetPixel(x, y, newColor);
            }
            return returnImage;
        }

        static byte[] colorNoiseChange(byte rValue, byte gValue, byte bValue)
        {
            byte[] color = new byte[3];
            color[0] = rValue;
            color[1] = gValue;
            color[2] = bValue;
            Random random = new Random();

            for (int counter = 0; counter < 3; counter++)
            {
                int count = random.Next(0, 3);
                if (color[count] < 64)
                {
                    color[count] = (byte)(color[count] - 32);
                }
                else if (color[count] < 128)
                {
                    color[count] = (byte)(color[count] - 96);
                }
                else if (color[count] < 192 && color[count] > 128)
                {
                    color[count] = (byte)(color[count] - 128);
                }
                else if (color[count] > 192 && color[count] < 224)
                {
                    color[count] = (byte)(color[count] + 64);
                }

                else if (color[count] > 224)
                {
                    color[count] = (byte)(color[count] + 32);
                }
            }
            return color;
        }
    }
}